//
//  searchViewTableViewController.m
//  Candy
//
//  Created by QUAQUA on 2018/3/21.
//  Copyright © 2018年 庄文盛 All rights reserved.
//

#import "searchViewTableViewController.h"
#import "search.h"
#import "ZUST.h"
#import "Header.h"
#import <AFNetworking.h>
#import "ShopModel.h"
#import "xianzhiViewController.h"

@interface searchViewTableViewController ()<UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate>{
    UITextField *_input;
    UISearchBar *customSearchBar;
    NSArray *arr;
    NSArray* searchData;
}
@property (nonatomic, strong) NSMutableArray *shopListSource;
@property (nonatomic, strong) NSMutableArray *searchModelDAta;
@property (nonatomic, strong) NSMutableArray *arrModelDAta;;
@end
bool isSearch;
@implementation searchViewTableViewController

- (NSMutableArray *)searchModelDAta {
    if (!_searchModelDAta) {
        _searchModelDAta = [NSMutableArray new];
    }
    return _searchModelDAta;
}

- (NSMutableArray *)arrModelDAta {
    if (!_arrModelDAta) {
        _arrModelDAta = [NSMutableArray new];
    }
    return _arrModelDAta;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    isSearch=YES;
    self.tableView.tableFooterView=[[UIView alloc]init];
    arr=[[NSArray alloc]initWithObjects:@"闲置打印网点",@"bbb",@"ccc", nil];
    UIButton *quxiao=[[UIButton alloc]initWithFrame:CGRectMake([UIScreen mainScreen].bounds.size.width-50, 20, 50, 44)];
    [quxiao setTitle:@"取消" forState:UIControlStateNormal];
    [quxiao addTarget:self action:@selector(quxiao) forControlEvents:UIControlEventTouchDown];
    
    self.navigationController.navigationBar.barTintColor=[UIColor whiteColor];
    customSearchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 20, [UIScreen mainScreen].bounds.size.width-50, 44)];
    [quxiao setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.navigationController.view addSubview:quxiao];
    
    //customSearchBar.showsCancelButton = YES;
    customSearchBar.searchBarStyle = UISearchBarStyleDefault;
    
    
    _input=[customSearchBar valueForKey:@"_searchField"];
    [_input setValue:[UIFont systemFontOfSize:12] forKeyPath:@"_placeholderLabel.font"];
    customSearchBar.delegate = self;
    customSearchBar.placeholder=@"输入附近服务点";
    customSearchBar.backgroundColor=[UIColor whiteColor];
    customSearchBar.layer.masksToBounds=YES;
    customSearchBar.layer.cornerRadius=5;
    customSearchBar.searchBarStyle=UISearchBarStyleMinimal;
    [self.navigationController.view addSubview:customSearchBar];
    [self.tableView registerNib:[UINib nibWithNibName:@"search" bundle:nil] forCellReuseIdentifier:@"sousuo"];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (NSMutableArray *)shopListSource {
    if (!_shopListSource) {
        _shopListSource = [NSMutableArray new];
    }
    return _shopListSource;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    //warning Incomplete implementation, return the number of sections
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 70;
};
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    xianzhiViewController *vc = [xianzhiViewController new];
    vc.model = self.shopListSource[indexPath.row];
    [self.navigationController pushViewController:vc animated:YES];
    [customSearchBar resignFirstResponder];
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    [self dismissViewControllerAnimated:YES completion:nil];
    NSLog(@"----searchBarCancelButtonClicked------");
    // 取消搜索状态
    [customSearchBar resignFirstResponder];
    //isSearch = NO;
    // [self dismissViewControllerAnimated:YES completion:nil];
    // [self.tableView reloadData];
}
#pragma mark - Table view data source
-(void)quxiao{
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    search *cell = [tableView dequeueReusableCellWithIdentifier:@"sousuo" forIndexPath:indexPath];
    NSInteger rowNo = indexPath.row;

    if(isSearch)
    {
        // 使用searchData作为表格显示的数据
        cell.name.text = [searchData objectAtIndex:rowNo];
       // [cell setCellValue:searchData[indexPath.row]];
       // cell.titleLable.text=[searchData2 objectAtIndex:rowNo];
    }
    else{
        // 否则使用原始的tableData作为表格显示的数据
        cell.name.text = [arr objectAtIndex:rowNo];
        

    }
  
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    //#warning Incomplete implementation, return the number of rows
    if(isSearch)
    {
        
        return searchData.count;
        
    }
    else
    {
        
        return arr.count;
        
    }
    
}

- (void)searchBar:(UISearchBar *)searchBar
    textDidChange:(NSString *)searchText
{
    NSLog(@"----textDidChange------");
    // 调用filterBySubstring:方法执行搜索
    [self filterBySubstring:searchText];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    NSLog(@"----searchBarSearchButtonClicked------");
    // 调用filterBySubstring:方法执行搜索
    [self filterBySubstring:searchBar.text];
    // 放弃作为第一个响应者，关闭键盘
    [customSearchBar resignFirstResponder];
}

- (void) filterBySubstring:(NSString*) subStr
{
    NSLog(@"----filterBySubstring------");
    // 设置为搜索状态
    isSearch = YES;
    // 定义搜索谓词
    NSPredicate* pred = [NSPredicate predicateWithFormat:
                         @"SELF CONTAINS[c] %@" , subStr];
    // 使用谓词过滤NSArray
    
    searchData = [arr filteredArrayUsingPredicate:pred];
    
    // 让表格控件重新加载数据
    [self.tableView reloadData];
}

- (void)getTask {
   // NSDictionary *parameters = @{@"contentValue":@"任务1"};
    AFHTTPSessionManager* session=[AFHTTPSessionManager manager];
    session.responseSerializer=[AFHTTPResponseSerializer serializer];
    [session GET:@"http://127.0.0.1:3000/?contentValue=任务1" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"下载成功");
        
        
        NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
        NSLog(@"res=%@",jsonObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"下载失败");
    }];
}

- (void)viewWillAppear:(BOOL)animated {
     [self getShop];
}

- (void)getShop {
    [SVProgressHUD showWithStatus:@"loding"];
    AFHTTPSessionManager* session=[AFHTTPSessionManager manager];
    session.responseSerializer=[AFHTTPResponseSerializer serializer];
    [session GET:SHOPHTTP parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"下载成功");
        [SVProgressHUD dismiss];
        id jsonObject = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        NSMutableArray *arr = (NSMutableArray *)jsonObject;
        [self.shopListSource removeAllObjects];
        for (NSDictionary *dic in arr) {
            ShopModel *model = [ShopModel mj_objectWithKeyValues:dic];
            [self.shopListSource addObject:model];
            [self.arrModelDAta addObject:model.shopName];
        }
        arr = self.arrModelDAta.copy;
        NSLog(@"%@",arr);
        //[self.tableView reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"下载失败");
    }];
}

@end
